<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cart extends MX_Controller {

	private $module = 'cart';
	private $table = 'cart';
	function __construct(){
		parent::__construct();
		
		$this->load->model($this->module.'_model','model');
		$this->load->model('admincp_modules/admincp_modules_model');
		$this->load->model('category/category_model','category');
		$this->load->model('products/products_model','productsModel');
		if($this->uri->segment(1)=='admincp'){
			if($this->uri->segment(2)!='login'){
				if(!$this->session->userdata('userInfo')){
					header('Location: '.PATH_URL.'admincp/login');
					return false;
				}
				$get_module = $this->admincp_modules_model->check_modules($this->uri->segment(2));
				$this->session->set_userdata('ID_Module',$get_module[0]->id);
				$this->session->set_userdata('Name_Module',$get_module[0]->name);
			}
			$this->template->set_template('admin');
			$this->template->write('title','Admin Control Panel');
		}
	}
	/*------------------------------------ Admin Control Panel ------------------------------------*/
	public function admincp_index(){
		modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'r',0);
		$default_func = 'created';
		$default_sort = 'DESC';
		$data = array(
			'module'=>$this->module,
			'module_name'=>$this->session->userdata('Name_Module'),
			'default_func'=>$default_func,
			'default_sort'=>$default_sort
		);
		$this->template->write_view('content','BACKEND/index',$data);
		$this->template->render();
	}
	
	
	public function admincp_update($id=0){
		if($id==0){
			modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'w',0);
		}else{
			modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'r',0);
		}
		$result[0] = array();
		if($id!=0){
			$result = $this->model->getDetailManagement($id);
			$price= $this->model->getPriceCart($id);
			$sp=$this->model->getSumSl($id);
			$arrayIdProduct=$this->model->getidProducts($id);
			
			foreach($arrayIdProduct as $r){
				$idProducts=$r->idProduct;
				$arrayPro=$this->productsModel->getOneIdProduct($idProducts);
			}
		}
		$data = array(
			'result'=>$result[0],
			'module'=>$this->module,
			'id'=>$id,
			'price'=>$price,
			'sp'=>$sp,
			'arrayIdProduct'=>$arrayIdProduct,
		);
		$this->template->write_view('content','BACKEND/ajax_editContent',$data);
		$this->template->render();
	}
	
	public function admincp_save(){
		$perm = modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'w',1);
		if($_POST){
			//Upload Image
			$fileName = array('image'=>'');
			if($_FILES){
				foreach($fileName as $k=>$v){
					if(isset($_FILES['fileAdmincp']['error'][$k])){
						$typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'][$k],0,5));
						if($typeFileImage == 'image'){
							$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
							$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
							$ext = strtolower(substr($file_name[$k], -4, 4));
							if($ext=='jpeg'){
								$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-5)).'.jpg';
							}else{
								$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).$ext;
							}
						}else{
							print 'Only upload Image.';
							exit;
						}
					}
				}
			}
			//End Upload Image
			
			if($this->model->saveManagement($fileName)){
				//Upload Image
				if($_FILES){
					foreach($fileName as $k=>$v){
						if(isset($_FILES['fileAdmincp']['error'][$k])){
							$upload_path = BASEFOLDER.IMAGES_PRODUCTS.$this->input->post('folderAdmincp').'/';
							move_uploaded_file($tmp_name[$k], $upload_path.$fileName[$k]);
						}
					}
				}
				//End Upload Image
				print 'success';
				exit;
			}
		}
	}
	
	public function admincp_delete(){
		$perm = modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'d',1);
		if($perm=='permission-denied'){
			print $perm;
			exit;
		}
		if($this->input->post('id')){
			$id = $this->input->post('id');
			$result = $this->model->getDetailManagement($id);
			$folderTmp=explode('/',$result[0]->image);
			modules::run('admincp/saveLog',$this->module,$id,'Delete','Delete');
			$this->db->where('id',$id);
			if($this->db->delete($this->table)){
				//Xóa hình khi Delete
				@unlink(BASEFOLDER.IMAGES_PRODUCTS.$folderTmp[0].'/'.$folderTmp[1]);
				return true;
			}
		}
	}
	
	public function admincp_ajaxLoadContent(){
		$this->load->library('AdminPagination');
		$config['total_rows'] = $this->model->getTotalsearchContent();
		$config['per_page'] = $this->input->post('per_page');
		$config['num_links'] = 3;
		$config['func_ajax'] = 'searchContent';
		$config['start'] = $this->input->post('start');
		$this->adminpagination->initialize($config);

		$result = $this->model->getsearchContent($config['per_page'],$this->input->post('start'));
		$data = array(
			'result'=>$result,
			'per_page'=>$this->input->post('per_page'),
			'start'=>$this->input->post('start'),
			'module'=>$this->module
		);
		$this->session->set_userdata('start',$this->input->post('start'));
		$this->load->view('BACKEND/ajax_loadContent',$data);
	}
	
	public function admincp_ajaxSelect(){
		$idCate=$this->input->post('idCate');
		$folder=$this->category->getFolder($idCate);
		$showTags='';
		foreach($folder as $r){
			$showTags .='<option value="'.$r->folder.'">'.$r->folder.'</option>';
		}
		print $showTags;
	}
	
	public function admincp_ajaxUpdateStatus(){
		$perm = modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'w',1);
		if($perm=='permission-denied'){
			print '<script type="text/javascript">show_perm_denied()</script>';
			$status = $this->input->post('status');
			$data = array(
				'status'=>$status
			);
		}else{
			if($this->input->post('status')==0){
				$status = 1;
			}else{
				$status = 0;
			}
			$data = array(
				'status'=>$status
			);
			modules::run('admincp/saveLog',$this->module,$this->input->post('id'),'status','update',$this->input->post('status'),$status);
			$this->db->where('id', $this->input->post('id'));
			$this->db->update($this->table, $data);
		}
		
		$update = array(
			'status'=>$status,
			'id'=>$this->input->post('id'),
			'module'=>$this->module
		);
		$this->load->view('BACKEND/ajax_updateStatus',$update);
	}
	/*------------------------------------ End Admin Control Panel --------------------------------*/
	
	
	/*------------------------------------ FRONTEND ------------------------------------*/
	
	public function index(){		
		$data=array(
			'module' => $this->module,
			'title' => 'Giỏ hàng',
		);
		$this->load->view('FRONTEND/index',$data);
	}
	
	public function addCart(){
		if($_POST){
			$proTmp=$this->productsModel->getOne($this->input->post('idProduct'));
			if($proTmp[0]->price_new !=0 && $proTmp[0]->promotion !=0){
				$price=$proTmp[0]->price_new;
			}else{
				$price=$proTmp[0]->price_old;
			}
				
			if($this->session->userdata('Cart')){
				$cart=$this->session->userdata('Cart');
				$stringCart=$cart['shop'];
				$checkId=strstr($stringCart,$this->input->post('idProduct').',');	
				
				if($checkId){
					$str_checkId=strtok($checkId,'|');
					$ar_checkId=explode(',',$str_checkId);
					$id=$ar_checkId[0];
					$qty='';
					if($this->input->post('qty')){
						$qty=$this->input->post('qty');
					}else{
						$qty =$ar_checkId[1]+1;
					}
					
					$str_add=$id.','.$qty.','.$ar_checkId[2];
					$str_end=str_replace($str_checkId,$str_add,$stringCart);
					$data=array(
						'shop' =>$str_end,
					);
					$this->session->set_userdata('Cart',$data);
					$this->load->view('FRONTEND/showcart');
				}else{
					if($this->input->post('qty')){
						$qty=$this->input->post('qty');
						$stringCart=$cart['shop'].''.$this->input->post('idProduct').','.$qty.','.$price.'|';
					}else{
						$stringCart=$cart['shop'].''.$this->input->post('idProduct').',1,'.$price.'|';
					}
					
					$data=array(
						'shop' => $stringCart,
					);
					$this->session->set_userdata('Cart',$data);
					$this->load->view('FRONTEND/showcart');
				}
				
			}else{
				if($this->input->post('qty')){
					$qty=$this->input->post('qty');
					$data=array(
						'shop' => ''.$this->input->post('idProduct').','.$qty.','.$price.'|',
					);
				}else{
					$data=array(
						'shop' => ''.$this->input->post('idProduct').',1,'.$price.'|',
					);
				}
				
				$this->session->set_userdata('Cart',$data);
				$this->load->view('FRONTEND/showcart');
			}	
		}
	}
	
	public function upCart(){
		if($_POST){
			if($this->session->userdata('Cart')){
				$cart=$this->session->userdata('Cart');
				$stringCart=$cart['shop'];
				$checkId=strstr($stringCart,$this->input->post('idProduct').',');
				if($checkId){
					$str_checkId=strtok($checkId,'|');
					$ar_checkId=explode(',',$str_checkId);
					$id=$ar_checkId[0];
					$qty=$this->input->post('qty');
					$str_add=$id.','.$qty.','.$ar_checkId[2];
					$str_end=str_replace($str_checkId,$str_add,$stringCart);
					$data=array(
						'shop' =>$str_end,
					);
					$this->session->set_userdata('Cart',$data);
					$this->load->view('FRONTEND/delcart');
				}
			}
		}
	}
	
	public function qtyCart(){	
		if($this->session->userdata('Cart')){		
			$cart=$this->session->userdata('Cart');
			$shop=rtrim($cart['shop'],'|');
			$arrShop=explode('|',$shop);
			$n=count($arrShop);
			$tong='';			
			if($arrShop[0]==''){
				$tong= '0';	
			}else{
				for($i=0;$i<$n;$i++){
					$arrTmp=explode(',',$arrShop[$i]);
					$tong +=$arrTmp[1];
				}
			}
			print $tong;
		}else{
			print '0';	
		}
	}
	
	public function delCart(){
		if($_POST){			
			if($this->session->userdata('Cart')){
				$cart=$this->session->userdata('Cart');
				$stringCart=$cart['shop'];
				$checkId=strstr($stringCart,$this->input->post('idProduct').',');
				if($checkId){
					$str_checkId=strtok($checkId,'|');
					$str_end=str_replace($str_checkId.'|','',$stringCart);
					if($str_end !=''){
						$data=array(
							'shop' =>$str_end,
						);
						$this->session->set_userdata('Cart',$data);
						if(!$this->input->post('del_check')){
							$this->load->view('FRONTEND/showcart');
						}else{
							$this->load->view('FRONTEND/delcart');
						}
					}else{
						$this->session->unset_userdata('Cart');
						if(!$this->input->post('del_check')){
							$this->load->view('FRONTEND/showcart');
						}else{
							$this->load->view('FRONTEND/delcart');
						}
					}
				}
			}
		}
	}
	
	public function eraseCart(){
		$this->session->unset_userdata('Cart');
		$this->load->view('FRONTEND/delcart');
	}
	
	public function checkout(){
		$data=array(
			'module' => $this->module,
			'title' => 'Thanh toán',
		);
		$this->load->view('FRONTEND/checkout',$data);
	}
	
	public function saveCheckout(){
		if($_POST){
			$data=array(
				'maHD' => $this->model->addCart(),
			);
			$this->session->unset_userdata('Cart');
			$this->load->view('FRONTEND/result',$data);
		}
	}
	
	public function DeletCartOne(){
		$this->db->where('id',$this->input->post('id'));
		$this->db->delete($this->table);
	}
	
	public function DeletCartOneHD(){
		$check=$this->model->getCartDetail($this->input->post('idCart'));
		
		$this->db->where('idCart',$this->input->post('idCart'));
		$this->db->where('idProduct',$this->input->post('id'));
		$this->db->delete($this->table.'_detail');
		
		$result=$this->model->getCartDetail($this->input->post('idCart'));
		$status=$this->model->getCartStatus($this->input->post('idCart'));
			
		if(count($check)==1){
			$this->db->where('id',$this->input->post('idCart'));
			$this->db->delete($this->table);
			print 'khong';
			exit;
		}else{
			$data=array(
				'result' => $result,
				'status' => $status,
				'id' => $this->input->post('idCart'),
			);
			$this->load->view('profile/FRONTEND/info_cart_detail_ajax',$data);
		}
	}
	
	/*------------------------------------ End FRONTEND --------------------------------*/ 
}